package com.yunda.nebula.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.yunda.nebula.gateway.service.RequestMatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * \* User: wei.zhang
 * \* Date: 2019/11/7 20:33
 * \* Description:
 * \
 */
@Slf4j
@Service
public class TokenAuthGatewayFilter implements GatewayFilter, Ordered {

    @Autowired
    private RequestMatcher requestMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取header的参数
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();
        if (!requestMatcher.match(path)){
            return chain.filter(exchange);
        }
        log.info("url {} 需要进行过滤!!!!",path);
        String token = serverHttpRequest.getHeaders().getFirst("token");
        if (StringUtils.isNoneBlank(token)) {
            return chain.filter(exchange);
        } else {
            exchange.getResponse().setStatusCode(HttpStatus.OK);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",HttpStatus.FORBIDDEN.value());
            jsonObject.put("msg","token is not existed!!!!");
            byte[] bytes = JSONObject.toJSONString(jsonObject).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Mono.just(buffer));
        }
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
